package com.yantu.controller.wx;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yantu.bean.User;
import com.yantu.mapper.UserMapper;
import com.yantu.util.GetUserInfoUtil;
import com.yantu.util.JWTUtil;
import com.yantu.util.Result;
import com.yantu.view.student.StudentUserView;
import com.yantu.view.wx.WxRegisterVM;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

@Api("微信端登录接口")
@RestController
@RequestMapping("/wx")
public class WxLoginController extends WxUserFatherController {

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    UserMapper userMapper;

    @ApiOperation("微信code登录")
    @PostMapping("/codeLogin/{code}")
    public Result wxCodeLogin(@NotBlank @PathVariable("code") String code) {
//@NotBlank注解只适用于string类型，且code去掉空格之后的size大于0
        //通过code换取信息
        JSONObject resultJson = GetUserInfoUtil.getResultJson(code);

        if (resultJson.has("openid")){
            //获取sessionKey和openId
//            String sessionKey = resultJson.get("session_key").toString();
            String openid = resultJson.get("openid").toString();
            System.out.println(openid);
            //查询用户是否存在
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("wx_open_id",openid);
            User user = userMapper.selectOne(query);
            System.out.println("用户信息存在吗？");
            System.out.println(user);
            if (user != null){//已授权，已绑定
                String token =  super.getUserToken(user);
                System.out.println(token);
                //数据库更新token
                UpdateWrapper queryUp = new UpdateWrapper<>();
                queryUp.eq("id",user.getId());
                queryUp.set("token",token);
                queryUp.set("loginTime",user.getLogintime());
                int result = userMapper.update(null,queryUp);
                String msg = "学生"+user.getUserName()+"微信登录成功";
                super.wxAddLog(user,msg);
                return Result.succ("登录成功", token); //用户存在，返回结果
            }else { //用户未授权
                return Result.fail("失败，微信账号未绑定");
            }
        }
        return Result.fail("授权失败"+ resultJson.getString("errmsg"));
    }

    //注册
    @PostMapping("/Register")
    @ApiOperation("微信用户注册")
    public Result wxRegister(@RequestBody WxRegisterVM wxRegisterVM){
        User user = new User();
        user.setPhone(wxRegisterVM.getPhone());
        user.setPassword(wxRegisterVM.getPassword());
        user.setRealName(wxRegisterVM.getRealName());
        user.setSex(wxRegisterVM.getSex());
        user.setUserName(wxRegisterVM.getUserName());
        user.setUserLevel(wxRegisterVM.getUserLevel());
        user.setStatus(1);
        user.setRole(1);
        User jwtUser = JWTUtil.setTime(user);
        int result = userMapper.insert(jwtUser);
        if(result>0){//注册成功，查出用户信息生成token
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_name", wxRegisterVM.getUserName());
            userQueryWrapper.eq("password", wxRegisterVM.getPassword());
            User user2 = userMapper.selectOne(userQueryWrapper);
            String token =  super.getUserToken(user);
            UpdateWrapper updateQuery = new UpdateWrapper<>();
            updateQuery.eq("id",user2.getId());
            updateQuery.set("loginTime",user2.getLogintime());
            updateQuery.set("expireTime",user2.getExpiretime());
            updateQuery.set("token",token);
            int updateNum = userMapper.update(null,updateQuery);//token存入表
            if(updateNum>0){
                String msg ="学生"+user.getUserName()+"注册账号成功";
                super.wxAddLog(user,msg);
                return Result.succ(200,"注册成功",token);
            }else {
                return Result.fail("存储token失败");
            }
        }else {
            String msg ="学生"+user.getUserName()+"注册账号失败";
            super.wxAddLog(user,msg);
            return Result.fail("注册失败");
        }
    }



    //解绑退出,也就是把用户wx_open_id删除
    @PutMapping("/loginOut/{token}")
    @ApiOperation("微信退出绑定")
    public Result wxLoginOut(@PathVariable String token){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("token",token);
        updateWrapper.set("wx_open_id","");
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("token",token);
        User user = userMapper.selectOne(userQueryWrapper);
        int result = userMapper.update(null,updateWrapper);
        if(result>0){
            String msg ="学生"+user.getUserName()+"微信退出绑定";
            super.wxAddLog(user,msg);
            return Result.succ("退出成功",null);
        }else {
            return Result.fail("退出失败");
        }
    }

    //用户名和密码登录
    @PostMapping("/accountLogin")
    @ApiOperation("学生端和微信端用户名和密码登录")
    public Result wxAccountLogin(@RequestBody StudentUserView studentUserView){

        //获取账号,获取密码
        String userName = studentUserView.getUsername();
        String password = studentUserView.getPassword();
        String token;
        //向数据库查询
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("user_name", userName)
                .eq("password", password);
        User user = userMapper.selectOne(query);
        System.out.println("在这里啦");
        System.out.println(user);
        if (user != null) {
            if (password.equals(user.getPassword())) { //一个简单的登录逻辑
                //给用户设置令牌的有效时间
                User jwtUser = JWTUtil.setTime(user);
                //将用户信息存到redis中
//                RedisUtils.saveValue(jwtUser.getId() + "", jwtUser, 30); //将用户信息存入redis数据库 第三和第四个参数为有效时间和时间单位
                //map用来存储放在payload中的信息有用户名和用户id
                token =  super.getUserToken(user);
                System.out.println("获取到token了");
                user.setToken(token);
                System.out.println(user);
                UpdateWrapper updateQuery = new UpdateWrapper<>();
                updateQuery.eq("id",user.getId());
                updateQuery.set("loginTime",user.getLogintime());
                updateQuery.set("expireTime",user.getExpiretime());
                updateQuery.set("token",token);
                int updateNum = userMapper.update(null,updateQuery);//token存入表
                System.out.println(updateNum);
                System.out.println(token);
                String msg ="学生"+user.getUserName()+"用户名和密码登录成功";
                super.wxAddLog(user,msg);
                return Result.succ(200, "登录成功", token);
            } else {
                String msg ="学生"+user.getUserName()+"用户名和密码登录失败";
                super.wxAddLog(user,msg);
                return Result.fail("登录失败111");
            }
        } else {
            String msg ="学生"+user.getUserName()+"用户名和密码登录失败";
            super.wxAddLog(user,msg);
            System.out.println("niyayayya");
            return Result.fail("登录失败222");
        }
    }

    @PostMapping("/bindCode")
    @ApiOperation("微信端用户名和密码的绑定")
    public Result wxBindCode(@RequestBody StudentUserView studentUserView){

        //获取账号,获取密码
        String userName = studentUserView.getUsername();
        String password = studentUserView.getPassword();
        String code  = studentUserView.getCode();
        String token;
        //向数据库查询
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("user_name", userName)
                .eq("password", password);
        User user = userMapper.selectOne(query);
        System.out.println("在这里啦");
        System.out.println(user);
        if (user != null) {//系统已有该用户名则和code绑定
            //解析code
            JSONObject resultJson = GetUserInfoUtil.getResultJson(code);

            if (resultJson.has("openid")){
                String openid = resultJson.get("openid").toString();

                token =  super.getUserToken(user);
                System.out.println("获取到token了");
                user.setToken(token);
                System.out.println(user);
                UpdateWrapper updateQuery = new UpdateWrapper<>();
                updateQuery.eq("id",user.getId());
                updateQuery.set("loginTime",user.getLogintime());
                updateQuery.set("expireTime",user.getExpiretime());
                updateQuery.set("token",token);
                updateQuery.set("wx_open_id",openid);
                int updateNum = userMapper.update(null,updateQuery);//token存入表
                System.out.println(updateNum);
                System.out.println(token);
                if(updateNum>0) {
                    String msg ="学生"+user.getUserName()+"微信绑定成功";
                    super.wxAddLog(user,msg);
                    return Result.succ(200, "绑定成功", token);
                }else {
                    String msg ="学生"+user.getUserName()+"微信绑定失败";
                    super.wxAddLog(user,msg);
                    return Result.fail("绑定失败");
                }
            } else {
                String msg ="学生"+user.getUserName()+"微信授权失败";
                super.wxAddLog(user,msg);
                return Result.fail("微信授权失败");
            }
        } else {//系统没有该用户名则添加人员并绑定
            User user1 = new User();
            user1.setUserName(userName);
            user1.setPassword(password);
            int result  = userMapper.insert(user1);

            //
            QueryWrapper<User> query2 = new QueryWrapper<>();
            query2.eq("user_name", userName)
                    .eq("password", password);
            User user2 = userMapper.selectOne(query);
            //解析code
            JSONObject resultJson = GetUserInfoUtil.getResultJson(code);

            if (resultJson.has("openid")) {
                String openid = resultJson.get("openid").toString();
                token = super.getUserToken(user);
                user.setToken(token);
                UpdateWrapper updateQuery = new UpdateWrapper<>();
                updateQuery.eq("id", user.getId());
                updateQuery.set("loginTime", user.getLogintime());
                updateQuery.set("expireTime", user.getExpiretime());
                updateQuery.set("token", token);
                updateQuery.set("wx_open_id", openid);
                int updateNum = userMapper.update(null, updateQuery);//token存入表
                String msg ="学生"+user.getUserName()+"微信绑定成功";
                super.wxAddLog(user,msg);
                return Result.succ("绑定成功", token);
            }
            String msg ="学生"+user.getUserName()+"微信绑定失败";
            super.wxAddLog(user,msg);
            return Result.fail("失败");
        }
    }

    @PostMapping("/scanLogin/{scanToken}")
    @ApiOperation("微信扫码登录")
    public Result scanLogin(HttpServletRequest request, @PathVariable String scanToken) {
        String token = request.getHeader("token");
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("token", token);
        User user = userMapper.selectOne(queryWrapper1);
        if (user != null) {
            if (scanToken != null && scanToken != "") {
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id", user.getId());
                updateWrapper.set("scan_token", scanToken);
                int result = userMapper.update(null, updateWrapper);
                if (result > 0) {
                    String msg ="学生"+user.getUserName()+"扫码成功";
                    super.wxAddLog(user,msg);
                    return Result.succ("成功", null);
                } else {
                    String msg ="学生"+user.getUserName()+"扫码失败";
                    super.wxAddLog(user,msg);
                    return Result.fail("扫码失败，请重新扫码");
                }
            } else {
                return Result.fail("所传参数为空");
            }
        } else {
            return Result.fail("该用户不存在");
        }
    }
}
